<template>
    <div>
        <div>
            <el-table :data="tableData" style="width: 100%" :default-sort="{ prop: 'phone', order: 'descending' }"
                :row-class-name="tableRowClassName" height="560px" size="mini" :highlight-current-row="true" stripe>
                <el-table-column label="序号" width="60">
                    <template slot-scope="scope">
                        {{ (scope.$index + 1) + (currentPage - 1) * pageSize }}
                    </template>
                </el-table-column>
                <el-table-column prop="avatar" label="头像" width="60">
                    <template slot-scope="scope">
                        <el-image :src="scope.row.avatar" class=" tableImg" v-if="scope.row.avatar"></el-image>
                        <div class="tableNoImg el-icon-picture-outline " v-else>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="phone" label="手机号" sortable>
                </el-table-column>
                <el-table-column prop="userName" label="姓名">
                </el-table-column>
                <el-table-column prop="nickName" label="昵称">
                </el-table-column>
                <el-table-column prop="sex" label="性别">
                    <template slot-scope="scope">
                        {{ scope.row.sex == 0 ? '男' : '女' }}
                    </template>
                </el-table-column>
                <el-table-column prop="userType" label="身份">
                    <template slot-scope="scope">
                        {{ scope.row.userType == 0 ? '管理员' : '普通用户' }}
                    </template>
                </el-table-column>
                <el-table-column prop="createdTime" label="创建" sortable>
                </el-table-column>
                <el-table-column prop="createdTime" label="操作" width="150">
                    <template slot-scope="scope">
                        <el-button type="info" size="small" @click="changeUserMess(scope.row)"
                            style="width: 50px;height:20px;">编辑</el-button>

                        <el-button type="danger" size="small" @click="deleteUser(scope.row)"
                            style="width: 50px;height:20px;">删除</el-button>
                    </template>

                </el-table-column>
            </el-table>
        </div>
        <div class="selectFind">
            <el-select v-model="selectFind" placeholder="请选择" style="width: 100px;">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
            </el-select>&nbsp;
            <el-input v-model="selectFindValue" placeholder="请输入内容" style="width: 400px;"></el-input>&nbsp;
            <el-button @click="selectFindbtn" type="primary" style="width: 70px;height:40px;">查询</el-button>
        </div>
        <div class="page">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
                :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

        <el-dialog :visible.sync="isChangeUserMess" :width="'800px'" :height="'400px'">
            <div slot="title" class="header-title">
                <span class="title-name">
                    <i class="el-icon-edit" style="margin-right:10px"></i>
                </span>
                <span class="title-age">用户信息修改</span>
            </div>
            <div class="changeUserMess" style="height: 400px;">
                <div class="menuLeft">
                    <el-upload class="avatar-uploader" action="api/util/uploadImg" name="imgFile" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :disabled="!messChange"
                        disabled="">
                        <img v-if="userChangeMess.avatar" :src="userChangeMess.avatar" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <div>
                        <el-button type="primary" class="uploadButton" @click="uploadButton" v-if="messChange">点击上传头像<i
                                class="el-icon-upload el-icon--right"></i></el-button>
                    </div>

                </div>
                <div class="menuRigth">
                    <el-form :model="userChangeMess" :rules="rules" ref="userChangeMess" label-width="100px" size="mini"
                        class="demo-ruleForm">
                        <el-form-item label="姓名：" size="mini">
                            <el-input v-if="messChange" v-model="userChangeMess.userName" class="menuUserName"></el-input>
                            <span v-else class="menuUserName">{{ userChangeMess.userName }}</span>
                            <div class="navbar">
                                <el-button @click="messchange" type="primary" icon="el-icon-edit"
                                    :style="changeDisplay ? display1 : display0" circle></el-button>
                                <ul :style="messChange ? width1 : width0">
                                    <el-button type="info" icon="el-icon-close" @click="cancellation" circle></el-button>
                                    <el-button type="danger" icon="el-icon-check" @click="confirmChange" circle></el-button>
                                </ul>
                            </div>
                        </el-form-item>
                        <el-form-item label="昵称：" prop="name">
                            <el-input v-model="userChangeMess.nickName" class="menuNickName" maxlength="8" v-if="messChange"
                                show-word-limit clearable></el-input>
                            <span v-else>{{ userChangeMess.nickName }}</span>

                        </el-form-item>
                        <el-form-item label="密码：">
                            <el-input v-if="messChange" v-model="userChangeMess.pass"></el-input>
                            <span v-else>{{ userChangeMess.pass }}</span>
                        </el-form-item>
                        <el-form-item label="身份：">
                            <el-select v-model="userChangeMess.userType" v-if="messChange" placeholder="请选择">
                                <el-option v-for="item in user_type" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                            <span v-else>{{ userChangeMess.userType == 0 ? '普通用户' : '管理员' }}</span>
                        </el-form-item>

                        <el-form-item label="性别：" prop="resource">
                            <el-radio-group v-if="messChange" v-model="userChangeMess.sex">
                                <el-radio label="0">男&nbsp;&nbsp;&nbsp;</el-radio>
                                <el-radio label="1">女</el-radio>
                            </el-radio-group>
                            <span v-else>
                                <span v-if="userChangeMess.sex == 0">男</span>
                                <span v-if="userChangeMess.sex == 1">女</span>
                            </span>

                        </el-form-item>
                        <el-form-item label="手机：">
                            <el-input v-if="messChange" v-model="userChangeMess.phone"></el-input>
                            <span v-else>{{ userChangeMess.phone }}</span>
                        </el-form-item>
                        <el-form-item label="邮箱：">
                            <el-input v-if="messChange" v-model="userChangeMess.email"></el-input>
                            <span v-else>{{ userChangeMess.email }}</span>
                        </el-form-item>

                    </el-form>
                </div>
            </div>
        </el-dialog>


        <!-- 弹出的页面内容 -->
        <el-dialog :visible.sync="uploadHeadImg" :width="'800px'">
            <div slot="title" class="header-title">
                <span class="title-name">
                    <i class="el-icon-edit" style="margin-right:10px"></i>
                </span>
                <span class="title-age">头像修改</span>
            </div>
            <div class="cropper-component">
                <!-- 工具箱部分 -->
                <div class="btn-box">

                    <div class="scope-btn">
                        <label class="btn" for="uploads"><i class="el-icon-download"></i>选择头像</label>
                        <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);"
                            accept="image/png, image/jpeg, image/gif, image/jpg, image/png"
                            @change="uploadImg($event, 'blob', 1)">
                        <el-button plain icon="el-icon-zoom-in" @click="changeScale(1)" type="info"
                            class="imgUtils">放大</el-button>
                        <el-button type="info" plain icon="el-icon-zoom-out" @click="changeScale(-1)"
                            class="imgUtils">缩小</el-button>
                        <el-button type="info" plain @click="rotateLeft" class="imgUtils"><i
                                class="el-icon-refresh-left"></i>左旋转</el-button>
                        <el-button type="info" plain @click="rotateRight" class="imgUtils"><i
                                class="el-icon-refresh-right"></i>右旋转</el-button>
                        <el-button type="danger" @click="upload()" class="imgUtils" style="width: 100px;">确认上传&nbsp;<i
                                class="el-icon-upload el-icon--right"></i></el-button>
                    </div>
                </div>
                <!-- 展示内容部分 -->
                <div class="show_box">
                    <!-- 展示选中图片 -->
                    <div class="cropper" :style="{ width: setWidth / 2 + 'px', height: setHeight / 2 + 'px' }">
                        <vueCropper ref="cropper" :img="option.img" :outputSize="option.size"
                            :outputType="option.outputType" :info="option.info" :full="option.full"
                            :canMove="option.canMove" :canMoveBox="option.canMoveBox" :original="option.original"
                            :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth"
                            :autoCropHeight="option.autoCropHeight" :enlarge="option.enlarge" :fixedBox="option.fixedBox"
                            @realTime="realTime" @imgLoad="imgLoad"></vueCropper>
                    </div>
                    <!-- 展示缩略图 -->
                    <div class="preview-box">
                        <div class="preview">
                            <img :src="previews.url ? previews.url : circleUrl"
                                :style="previews.url ? previews.img : 'width:130px;height:140px'" />
                        </div>
                        <div style="margin-left: 40px;">
                            <span style="left: 50px;">头像预览</span>
                        </div>
                    </div>
                </div>

            </div>
            <div>
                <span style="color: red;">*</span>
                <span>&nbsp;仅支持jpg,npg,jpeg格式的图片上传，图片大小不超10MB</span>
            </div>
        </el-dialog>



    </div>
</template>
  
<script>

export default {
    props: {
        setWidth: {
            type: Number,
            default: 400
        },
        setHeight: {
            type: Number,
            default: 400
        }
    },
    data() {
        return {
            //剪切图片上传
            crap: false,
            previews: {},
            option: {
                img: '', // 裁剪图片的地址
                info: false, // 裁剪框的大小信息
                outputSize: 1, // 剪切后的图片质量（0.1-1）
                outputType: 'jpg', // 裁剪生成的图片的格式
                canMove: true,  // 上传图片是否可以移动
                original: false,  // 上传图片是否显示原始宽高
                canMoveBox: true,  // 截图框能否拖动
                autoCrop: true, // 是否默认生成截图框
                autoCropWidth: this.setWidth / 3,
                autoCropHeight: this.setHeight / 3,
                fixedBox: true, // 截图框固定大小
                fixed: false, //是否开启截图框宽高固定比例
                enlarge: 3,//图片根据截图框输出比例倍数

            },
            fileName: '',  // 本机文件地址
            downImg: '#',
            imgFile: '',
            uploadImgRelaPath: '', // 上传后的图片的地址（不带服务器域名）
            myUserType:JSON.parse(sessionStorage.getItem("userMess")).userType,


            activeName: 'first',
            circleUrl: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
            userMess: {},
            uploadHeadImg: false,
            messChange: false,
            changeDisplay: false,
            width0: 'width:0px',
            width1: 'width:90px',
            display0: '',
            display1: 'display:none',
            userChangeMess: {},
            avatar: '',
            rules: {
                name: [
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],

            },

            tableData: [
            ],
            options: [{
                value: 'phone',
                label: '电话'
            }, {
                value: 'user_name',
                label: '姓名'
            }, {
                value: 'nick_name',
                label: '昵称'
            }, {
                value: '',
                label: '全部'
            }],
            user_type: [{
                value: '0',
                label: '普通用户'
            }, {
                value: '1',
                label: '管理员'
            }],
            selectFind: '',
            selectFindValue: '',
            currentPage: 1,
            pageSize: 10,
            total: 0,
            isSelectFind: false,
            selectValue: '',
            inputValue: '',
            isChangeUserMess: false,



        }
    },
    created() {
        this.findUserMess();

    },
    methods: {
        tableRowClassName({ row, rowIndex }) {
            if (rowIndex % 2 === 1) {
                return 'success-row';
            } else if (rowIndex % 2 === 0) {
                return 'warning-row';
            }
            return '';
        },
        deleteUser(row) {
            this.$confirm('是否删除昵称为' + row.nickName + '的用户?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get("api/wqunAccountController/deleteById?id=" + row.id).then((res) => {
                this.$message({
                    type: res.data.success ? 'success' : 'error',
                    message: res.data.message,
                })
                if(res.data.success){
                    this.findUserMess();
                }
            })
            }).catch(() => {});
        },


        uploadButton() {
            this.uploadHeadImg = true;
        },
        messchange() {
            this.messChange = true;
            this.changeDisplay = true;
        },
        cancellation() {
            this.userChangeMess = this.userMess;
            this.messChange = false;
            setTimeout(() => {
                this.changeDisplay = false;
            }, 500);

        },
        confirmChange() {
            this.$confirm('是否修改昵称为' + this.userMess.nickName + '用户的信息?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.post("api/wqunAccountController/changeAccount", this.userChangeMess).then((res) => {
                    if (res.data.success) {
                        this.$message({
                            message: '修改成功',
                            type: 'success'
                        })
                        this.messChange = false;

                        setTimeout(() => {
                            this.changeDisplay = false;
                        }, 500);
                        this.findUserMess();
                        this.isChangeUserMess = false;
                    } else {
                        this.$message({
                            message: res.data.message,
                            type: 'error'
                        })
                    }
                });
            }).catch(() => {

            });


        },
        init() {
            
            this.userChangeMess = this.userMess;
        },
        handleClick(tab, event) {

        },
        //图片上传
        handleAvatarSuccess(res) {
            if (res.success) {
                this.userChangeMess.avatar = res.data.resPath
                this.$message({
                    type: 'success',
                    message: ""
                })
            } else {
                this.$message({
                    type: 'error'
                })
            }
        },
        beforeAvatarUpload(file) {
            const isJPG = (file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png');
            const isLt2M = file.size / 1024 / 1024 < 4;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG和PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    alert('submit!');
                } else {
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },

        // 放大/缩小
        changeScale(num) {
            num = num || 1;
            this.$refs.cropper.changeScale(num);
        },
        // 坐旋转
        rotateLeft() {
            this.$refs.cropper.rotateLeft();
        },
        // 右旋转
        rotateRight() {
            this.$refs.cropper.rotateRight();
        },
        // 上传图片（点击上传按钮）
        finish(type) {
            let formData = new FormData();
            // 输出
            if (type === 'blob') {
                this.$refs.cropper.getCropBlob((data) => {
                    let img = window.URL.createObjectURL(data);
                    formData.append('file', data, 'da.jpg');
                    this.$emit('postFile', formData);
                })
            } else {
                this.$refs.cropper.getCropData((data) => {
                    formData.append('images', data);
                    this.$emit('postFile', formData);
                })
            }
        },
        // 实时预览函数
        realTime(data) {
            this.previews = data;
        },

        // 上传图片到服务器
        upload() {
            var aLink = document.createElement('a');
            let timer = new Date().getTime()
            aLink.download = timer;//文件名
            // 获取截图的blob数据
            this.$refs.cropper.getCropBlob((data) => {
                let file = new window.File([data], this.fileName, { type: 'image/jpeg,image/png' })
                var formData = new FormData();
                formData.append('imgFile', file);
                this.$axios.post("api/util/uploadImg", formData).then((res) => {

                    if (res.data.success) {
                        this.userChangeMess.avatar = res.data.data.resPath;
                        this.uploadHeadImg = false;
                        this.$message({
                            message: "图片上传成功",
                            type: 'success',
                        })
                    } else {
                        this.$message({
                            message: "图片上传成功失败，请检查网络",
                            type: 'error',
                        })
                    }
                });
            })
        },

        // 选择本地图片
        uploadImg(e, type, num) {//num代表第几个
            // 上传图片
            var file = e.target.files[0];
            this.fileName = file.name;
            if (!/\.(jpg|png)$/.test(e.target.value)) {
                this.$message.info('证件照图片必须是jpg格式');
                return false;
            }
            let reader = new FileReader();
            reader.onload = (e) => {
                let data = '';//生成图片地址
                if (typeof e.target.result === 'object') {
                    if (type == 'blob') {
                        // 把Array Buffer转化为blob 如果是base64不需要
                        data = window.URL.createObjectURL(new Blob([e.target.result]));
                    }
                }
                else {
                    data = e.target.result;
                }
                if (num === 1) {
                    this.option.img = data;
                }
            }
            if (type == 'blob') {
                // 转化为blob
                reader.readAsArrayBuffer(file);
            } else {
                // 转化为base64
                reader.readAsDataURL(file);
            }
        },
        //图片加载的回调 imgLoad 返回结果success, error
        imgLoad(msg) {

        },
        //刷新-清除截图
        // refeshImg(type){
        //   if(type == 'start'){
        //     this.$refs.cropper.startCrop() //开始截图
        //   }else if(type == 'end'){
        //     this.$refs.cropper.stopCrop() //停止截图
        //   }else if(type == 'clear'){
        //      this.$refs.cropper.clearCrop() //清除截图
        //   }

        // }
        changeUserMess(row) {
            this.isChangeUserMess = true;
            this.userChangeMess = row;
            this.userMess = row;
        },

        findUserMess() {
            if(this.myUserType != 1){
                this.$router.push({
                    name:"login",
                })
            }
            if (this.isSelectFind) {
                this.$axios.get("api/wqunAccountController/findAccountPage?pageSize=" + this.pageSize + "&currentPage=" + this.currentPage + "&selectValue=" + this.selectValue + "&inputValue=" + this.inputValue).then((res) => {
                    if (res.data.success) {
                        this.tableData = res.data.data.findAccountPage;
                        this.total = res.data.data.total;
                    }
                },)
            } else {
                this.$axios.get("api/wqunAccountController/findAccountPage?pageSize=" + this.pageSize + "&currentPage=" + this.currentPage + "&selectValue=" + "" + "&inputValue=" + "").then((res) => {
                    if (res.data.success) {
                        this.tableData = res.data.data.findAccountPage;
                        this.total = res.data.data.total;
                    }
                },)
            }

        },
        selectFindbtn() {
            this.selectValue = this.selectFind;
            if (this.selectFindValue == "") {
                this.inputValue = "NULL";
            } else {
                this.inputValue = this.selectFindValue;
            }
            this.isSelectFind = true;
            this.currentPage = 1;
            this.findUserMess();
        },

        handleSizeChange(val) {
            this.pageSize = val;
            this.findUserMess();

        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.findUserMess();
        },
        getAllUser() {

            this.findUserMess();
        }
    }
}
</script>



<style>
.el-table .warning-row {
    background: #e7e6e6;
}

.el-table .success-row {
    background: #7ff5df;
}

.el-table tbody tr:hover>td {
    background-color: #cccccc !important;
}
</style>



<style scoped>
* {
    font-family: "Hiragino Sans GB"
}

* {
    margin: 0;
    padding: 0;
}




.imgUtils {
    width: 80px;
    height: 30px;
}

.cropper-component {
    width: 800px;
    height: 350px;
    margin: 0 auto;
    position: relative;

    .btn-box {
        margin: 20px 0;
        margin-left: 00px;


        .btn {
            outline: none;
            display: inline-block;
            line-height: 1;
            white-space: nowrap;
            cursor: pointer;
            text-align: center;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            outline: 0;
            -webkit-transition: .1s;
            transition: .1s;
            font-weight: 500;
            padding: 8px 15px;
            font-size: 14px;
            border-radius: 3px;
            color: #fff;
            background-color: #409EFF;
            border-color: #409EFF;
            margin-right: 10px;
            height: 28px;

        }
    }

    .show_box {
        display: flex;
        position: absolute;
        left: 70px;
        top: 80px;


        .cropper {
            margin-left: 50px;
        }

        .preview-box {
            margin-left: 170px;
            top: 60px;
            left: 10px;

            .preview {
                width: 130px;
                height: 135px;
                border: 1px solid #ccc;
                background-color: #ccc;
                margin: 5px;
                overflow: hidden;
            }
        }
    }

}

.uploadHeadImg {
    border: solid 1px red;

    height: 400px;
}

.uploadButton {
    margin: 30px;
    width: 130px;
    height: 35px;
}

body {
    height: 100vh;
    /* 背景渐变 */
    background: linear-gradient(200deg, #ddd6f3, #faaca8);
}

/* 三个元素都需要弹性布局，所以写在一块 */
body,
.navbar,
.navbar ul {
    display: flex;
    justify-content: center;
    align-items: center;
}

.navbar {
    position: absolute;
    left: 160px;
    bottom: 15px;
    justify-content: center;
    align-items: center;
    height: 0px;
}


.navbar ul {
    /* 溢出隐藏 */
    overflow: hidden;
    /* 在这里加个过渡，可以让展开和收起自然一些 */
    transition: all 0.5s;
    /* 让文字不换行显示 */
    white-space: nowrap;
}

.navbar ul li {
    list-style: none;
    margin: 0px 15px;
}



.demo-ruleForm {
    width: 500px;
}

.menuNickName {
    width: 50%;
    margin-right: 30px;
    display: inline-block;
}

.menuUserName {
    width: 40%;
    margin-right: 30px;
    display: inline-block;
}

.menuRigth el-input {
    display: inline;
}

.menuLeft {
    float: left;
}

.menuRigth {
    margin: 10px;
    margin-left: 30px;
    float: left;
}

.avatar {
    height: 200px;

}

.avatar-uploader {
    height: 200px;
    width: 200px;

}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}



.userHeadImg {
    position: relative;
    top: 40px;
    left: 40px;
}

.mess {
    position: relative;
    top: -90px;
    left: 200px;
    width: 700px;
    height: 130px;
}

.mess span {
    margin-top: 240px;
    color: #676565;

}

.mess span:first-child {
    font-size: 30px;
    color: #676565;

}



.menu {
    padding: 20px
}

.userMess {
    height: 200px;
}

.contianer {}

.baseMess {
    border: solid 1px #cccccc;
    width: 1000px;
    height: 600px;
    margin: 0 auto;
    border-radius: 20px
}
</style>














<style  scoped>
.selectFind {
    margin-top: 10px;
    margin-right: 60px;
    float: left;
}

.contianer {
    height: 500px;
}

.tableImg {
    width: 30px;
    height: 30px;
}

.page {
    margin-top: 20px;
    margin-right: 60px;
    float: right;
}

.tableNoImg {

    width: 30px;
    height: 30px;
    margin-left: 7px;

}
</style>